import comm from './core';
import * as test from './test';

function transformMediaData (data) {
  const {
    code,
    displayName,
    subtitle,
    bigPic,
    smallPic,
    lunboPic,
    area,
    age,
    year,
    score,
    description,
    director,
    actors,
    tags,
    tagCode,
    videoType,
    isChargeable,
    contentPackageQueryDtos,
    price,
    stat,
    mediaDtos
  } = data;
  const duration = (data.duration / 60).toFixed(2) || 0;

  let mediaDto = {};
  if (mediaDtos) {
    for (const item of mediaDtos) {
      if (item.source === 'vr_share' && item.status === 1 && (item.renderType.length === 0 || item.renderType.trim() === '360_2D')) {
        mediaDto = item;
        break;
      }
    }
  }
  let itemPrice = (price / 100).toFixed(2);
  if (contentPackageQueryDtos) {
    itemPrice = (contentPackageQueryDtos[0].price / 100).toFixed(2);
  }

  const bigImage = bigPic || smallPic || lunboPic;
  return {
    sid: code,
    title: displayName,
    subtitle,
    bigImage: comm.formatZoomPic(bigImage),
    smallImage: comm.formatZoomPic(smallPic) || comm.formatZoomPic(bigPic),
    score: (+score).toFixed(1),
    scoreSeries: comm.dealScore(score),
    intro: description,
    area,
    year: age || year,
    directors: director.split(';'),
    actors: actors.split(';'),
    duration: duration.split('.')[0] + '′' + duration.split('.')[1] + '″',
    tags: (tags && tags.length > 0) ? tags.split('-') : [],
    tagCode,
    isChargeable: !!isChargeable,
    price: itemPrice,
    videoType: videoType,
    videoPath: mediaDto ? mediaDto.playUrl : '',
    playCount: comm.dealNumber(stat.playCount) || 0
  };
}

function get () {
  const params = comm.requestParams();

  const {
    origin,
    code,
    status
  } = params;
  if (!status || status !== 1) {
    return {};
  }

  const path = `program/findByCode`;
  const query = `code=${code}`;
  return comm.request({ origin, path, query }).then(({ data }) => {
    if (data) {
      return transformMediaData(data) || {};
    }
  });
}
function postUserFace ({ userID, accessToken, selfieImage }) {
  return new Promise((resolve, reject) => {
    test.ajax({
      url: 'https://stage.oben.me/generateHeadModel;sync=validation',
      method: 'POST',
      headers: {
        userID,
        accessToken
      },
      data: selfieImage,
      onSuccess (response) {
        resolve(response);
      },
      onError (error) {
        reject(error);
      }
    });
  });
}
export default {
  get,
  postUserFace
};
